class ServoModule {
  constructor(deviceId) {
    this.angle = 90; // 初始角度为90度（中间位置）
    this.topic = 'device/servo'; // 舵机控制主题
    this.stateTopic = 'device/servo/state'; // 舵机状态发布主题
    this.minAngle = 0; // 最小角度
    this.maxAngle = 180; // 最大角度
    this.deviceId = deviceId;
  }

  // 初始化舵机模块
  async init(mqttConnector) {
    this.mqttConnector = mqttConnector;
    await this.mqttConnector.subscribe(this.topic);
    this.mqttConnector.onMessage(this.handleMessage.bind(this));
    console.log('舵机模块已初始化');
    // 发布初始状态
    this.publishState();
  }

  // 处理接收到的消息
  handleMessage(topic, message) {
    if (topic === this.topic) {
      try {
        // 只处理JSON格式消息
        const command = message;
        if (command.type === 'control-command' && command.command) {
          if (command.command.action === 'set-angle' && typeof command.command.angle === 'number') {
            this.setAngle(command.command.angle);
          } else {
            console.log(`未知的舵机命令或参数: ${JSON.stringify(command.command)}`);
          }
        } else {
          console.log(`无效的舵机命令格式: ${JSON.stringify(message)}`);
        }
      } catch (error) {
        console.error(`处理舵机命令错误: ${error.message}`);
      }
    }
  }

  // 设置舵机角度
  setAngle(angle) {
    // 确保角度在有效范围内
    if (angle < this.minAngle) {
      angle = this.minAngle;
    } else if (angle > this.maxAngle) {
      angle = this.maxAngle;
    }

    this.angle = Math.round(angle); // 四舍五入到整数角度
    console.log(`舵机已设置到 ${this.angle} 度`);
    this.publishState();
  }

  // 增加角度
  increaseAngle(step = 5) {
    this.setAngle(this.angle + step);
  }

  // 减少角度
  decreaseAngle(step = 5) {
    this.setAngle(this.angle - step);
  }

  // 发布舵机状态
  async publishState() {
    const stateMessage = {
      deviceId: this.deviceId,
      timestamp: Date.now(),
      type: 'sensor-data',
      data: {
        value: this.angle+"",
        unit: 'degree',
        status: 'normal'
      }
    };
    await this.mqttConnector.publish(this.stateTopic, JSON.stringify(stateMessage));
  }

  // 设置角度范围
  setAngleRange(min, max) {
    this.minAngle = min;
    this.maxAngle = max;
    console.log(`舵机角度范围已设置: ${min}度 - ${max}度`);
  }
}

module.exports = ServoModule;